<template>
    <el-dialog
        class="custom-modal"
        :title="title"
        :visible.sync="show"
        append-to-body
        top="20vh"
        @open="_open"
        @close="_close"
        @closed="_afterClose"
        v-auto-focus
    >
        <div class="send-range-box">
            <div class="send-range__data-box">
                <div class="send-range__header">
                    <el-input
                        placeholder="请输入内容"
                        prefix-icon="el-icon-search"
                        v-model="search"
                        @input="handleInputChange"
                    >
                    </el-input>
                </div>
                <div class="send-range__body">
                    <el-tree
                        :data="treeData"
                        show-checkbox
                        default-expand-all
                        node-key="id"
                        ref="treeRef"
                        :check-strictly="isSingle"
                        highlight-current
                        :default-checked-keys="select"
                        @check-change="handleNodeClick"
                        :props="defaultProps"
                    >
                    </el-tree>
                </div>
            </div>
            <div class="send-range__data-box">
                <div class="send-range__header">
                    已选择{{selectData.length}}个
                </div>
                <div class="send-range__body">
                    <ul class="send-range__ul">
                        <template v-for="(item,index) in selectData">
                            <li class="send-range__li" :key="item.id" @click="handleDataClick(item, index)">
                                {{item.label}}
                            </li>
                        </template>
                    </ul>
                </div>
            </div>
        </div>
        <div slot="footer" class="dialog-footer">
            <el-button @click="close">取消</el-button>
            <el-button
                class="sure"
                type="primary"
                @click="sure"
                :loading="ajaxLoader"
                >保存</el-button
            >
        </div>
    </el-dialog>
</template>

<script lang="ts">
import { Component, Vue } from "vue-property-decorator";

@Component
export default class SendRangeForm extends Vue {
    title = "发送范围";
    show = false;
    ajaxLoader = false;
    ajaxIndex = 0;
    defaultProps = {
        children: "children",
        label: "label"
    };

    isSingle = false;

    model: any = {};
    search = "";
    treeData: any[] = [];
    // treeData: any[] = [
    //     {
    //         id: 1,
    //         label: "一级 1",
    //         children: [
    //             {
    //                 id: 4,
    //                 label: "二级 1-1",
    //                 children: [
    //                     {
    //                         id: 9,
    //                         label: "三级 1-1-1"
    //                     },
    //                     {
    //                         id: 10,
    //                         label: "三级 1-1-2"
    //                     }
    //                 ]
    //             }
    //         ]
    //     },
    //     {
    //         id: 2,
    //         label: "一级 2",
    //         children: [
    //             {
    //                 id: 5,
    //                 label: "二级 2-1"
    //             },
    //             {
    //                 id: 6,
    //                 label: "二级 2-2"
    //             }
    //         ]
    //     },
    //     {
    //         id: 3,
    //         label: "一级 3",
    //         children: [
    //             {
    //                 id: 7,
    //                 label: "二级 3-1"
    //             },
    //             {
    //                 id: 8,
    //                 label: "二级 3-2"
    //             }
    //         ]
    //     }
    // ];

    // 已选回显（右侧）
    selectData: any[] = [];
    // tree中选中的
    select: any[] = [];
    disabledList: any[] = [];
    multiple = false;
    async _open() {
        this.$emit("onopen");
        this.initData();
    }

    _close() {
        this.$emit("onclose");
    }

    _afterClose() {
        this.$nextTick(function() {
            this.$emit("onafterclose");
            this.$el.remove && this.$el.remove();
        });
    }

    loader(state: boolean) {
        if (state) {
            if (this.ajaxIndex === 0) this.ajaxLoader = true;
            this.ajaxIndex++;
        } else {
            setTimeout(() => {
                this.ajaxIndex--;
                if (this.ajaxIndex === 0) this.ajaxLoader = false;
            }, 300);
        }
    }

    close() {
        this.show = false;
        this.$nextTick(() => {
            this._afterClose();
        });
    }

    async initData() {
        this.loader(true);
        // 筛选标签
        try {
            const response = await this.$server["moduleManage/form/range"]({
                loader: false,
                data: {
                    name: this.search
                }
            });
            if (response.data.code !== 200 ||
                response.data.data === null) {
                throw response.data;
            }
            this.loader(false);
            const data = response.data.data || [];
            this.treeData = this.buildTableData(data);
        } catch (error) {
            if (error.cancel) {
                return;
            }
            // this.loader(false);
            this.$message.error(error.message || "接口请求错误!");
            throw error;
        }
    }

    buildTableData(list: any) {
        const res: any[] = [];
        if (list.length === 0) {
            return res;
        }
        const useList: any[] = [];
        list.forEach((item: any) => {
            if (item.length) {
                useList.push({
                    deptName: item[0].departmentName || "",
                    children: item
                });
            }
        });
        useList.forEach((cur: any, index: any) => {
            const _cur: any = {};
            _cur.label = cur.deptName || "";
            _cur.id = index + "key";
            if (cur.children && cur.children.length > 0) {
                _cur.children = cur.children.map((subCur: any) => {
                    const _subCur: any = {
                        label: subCur.name || "",
                        id: subCur.id || ""
                    };
                    if (this.select.includes(_subCur.id)) {
                        const _index = this.selectData.findIndex((selectItem: any) => selectItem.id === _subCur.id);
                        if (_index === -1) {
                            this.selectData.push(_subCur);
                        }
                    }
                    if (this.disabledList.includes(_subCur.id)) {
                        _subCur.disabled = true;
                    }
                    return _subCur;
                });
                res.push(_cur);
            }
        });
        return res;
    }

    async sure() {
        this.$emit("sure", {
            select: this.select
        });
    }

    handleInputChange() {
        this.initData();
    }

    handleNodeClick(item: any, checked: boolean) {
        const { id }: any = item;
        if (item.children && item.children.length > 0) return;
        if (this.isSingle) {
            if (checked) {
                (this.$refs.treeRef as any).setCheckedKeys([id]);
                this.select = [id];
                this.selectData = [item];
            } else {
                const _index = this.select.findIndex((cur: any) => cur === id);
                if (_index !== -1) {
                    this.select.splice(_index, 1);
                    this.selectData.splice(_index, 1);
                }
            }
        } else {
            const _index = this.select.findIndex((cur: any) => cur === id);
            if (_index === -1) {
                this.select.push(item.id);
                this.selectData.push(item);
            } else {
                const _itemIndex = this.selectData.findIndex((cur: any) => cur.id === id);
                this.select.splice(_index, 1);
                this.selectData.splice(_itemIndex, 1);
            }
        }
    }

    handleDataClick(item: any) {
        if (!this.disabledList.includes(item.id)) {
            const treeRef: any = this.$refs.treeRef;
            treeRef.setChecked(item.id);
        }
        // this.select.splice(index, 1);
        // this.selectData.splice(index, 1);
    }
}
</script>
<style scoped lang="scss">
.custom-modal {
    margin: 0;
    & /deep/ {
        .el-dialog {
            width: 800px;
        }
    }
    .send-range-box {
        width: 100%;
        height: 7rem;
        @include flexLayout(flex, normal, normal);
        .send-range__data-box {
            width: 100%;
            flex: 1;
            @include flexLayout(flex, normal, normal);
            flex-flow: column;
        }
        .send-range__header {
            flex: 0 0 auto;
            height: 0.6rem;
            padding-bottom: .2rem;
            @include textEllipsis();
            @include flexLayout(flex, center, center);
        }
        .send-range__body {
            flex: 1;
            height: calc(100% - 0.6rem);
            overflow: auto;
        }
        .send-range__ul {
            width: 100%;
            .send-range__li {
                padding: 0 0.2rem;
                height: 0.4rem;
                @include textEllipsis();
                @include flexLayout(flex, normal, center);
                cursor: pointer;
                & + .send-range__li {
                    border-top: 1px solid #eee;
                }
                &:hover {
                    background: #eee;
                }
            }
        }
    }
}
</style>
